/* eslint-disable prettier/prettier */
<template>
  <div>
    <el-card style="margin-bottom: 10px">
      <el-row :gutter="20">
        <el-col :span="2">
          <el-button type="danger" :icon="Back" style="font-size: 20px; padding: 0 6px" @click="turnBack()"></el-button>
        </el-col>
      </el-row>
    </el-card>
    <el-card style="padding-bottom:">
      <div class="flex gap-2 mt-4">
        <span>机组</span>
        <el-tag
          v-for="item in units_tag"
          :key="item.value"
          :checked="item.checked"
          @click="TagChange(item)"
          :type="item.checked ? 'primary' : 'info'"
          effect="light"
          round
          style="margin-left: 10px"
        >
          {{ item.value }}
        </el-tag>
      </div>
      <!--可扩展更多可用来筛选的tag-->
    </el-card>
    <el-row :gutter="10">
      <el-col :span="showMap ? 6 : 24">
        <el-card class="marker-list" body-style="padding: 0 10px" style="height: 100%">
          <template #header>
            <span>可选点位列表</span>
            <el-button type="primary" size="small" style="float: right" @click="OpenAddMarkerDialog">添加点位</el-button>
            <el-button size="small" style="float: right; margin-right: 10px" @click="showMapOrNot">{{
              showMap ? "收起地图" : "展开地图"
            }}</el-button>
            <el-button size="small" style="float: right" @click="clearFilter">重置列表</el-button>
          </template>
          <el-table
            ref="tableRef"
            :data="tableData"
            class="custom-table"
            border
            @selection-change="handleSelectionChange"
            v-loading="loading"
            height="100%"
          >
            <el-table-column type="selection" width="55" />
            <el-table-column prop="mapDetailDesc" label="点位名称"></el-table-column>
            <el-table-column
              prop="unitName"
              label="机组"
              :filters="units"
              :filter-method="filterUnit"
              filter-placement="bottom-end"
            >
            </el-table-column>
            <el-table-column prop="nfcName" label="点位编码"></el-table-column>
            <el-table-column label="操作" width="100" fixed="right">
              <template #default="scope">
                <el-button type="primary" @click="goToMarker(scope.row)" size="small" text style="padding: 0 0">查看</el-button>
                <!--                <el-button type="danger" @click="deleteMarker(scope.row)" size="small" text style="padding: 0 0">删除</el-button>-->
              </template>
            </el-table-column>
          </el-table>
          <template #footer>
            <div style="width: 100%; display: flex; justify-content: center">
              <el-button type="success" @click="OpenNewMapDialog" style="margin-top: -10px">新建路线</el-button>
            </div>
          </template>
        </el-card>
      </el-col>
      <el-col :span="18">
        <el-card id="map-container" v-show="showMap"> </el-card>
        <div id="panel" v-show="showMap"></div>
      </el-col>
    </el-row>
    <el-dialog title="新建路线" v-model="showNewMapDialog" width="30%">
      <!-- 表单 -->
      <el-form :model="addForm" ref="addFormRef" label-width="120px" :rules="addRules">
        <el-form-item label="路线名称" prop="mapName">
          <el-input v-model="addForm.mapName"></el-input>
        </el-form-item>
      </el-form>
      <!-- 对话框底部按钮 -->
      <template #footer>
        <el-button @click="showNewMapDialog = false">取消</el-button>
        <el-button type="primary" @click="ConfirmNewMap">提交</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="js">
import { onMounted, onUnmounted, reactive, ref } from "vue";
import AMapLoader from "@amap/amap-jsapi-loader";
import { Back } from "@element-plus/icons-vue";
import request from "@/api/request.js";
import { ElMessage } from "element-plus";
import iconImage1 from "@/assets/icons/locationpng.png";
import iconImage2 from "@/assets/icons/red_location_icon.png";

let map = null;
let icon = null;
let icon2 = null;
const longitude = ref(); // 默认经度
const latitude = ref(); // 默认纬度
const showNewMapDialog = ref(false);
const loading = ref(true);
const addForm = reactive({
  mapName: "",
  mapPoints: []
});
const addFormRef = ref(null);
const addRules = {
  mapName: [{ required: true, message: "请输入路线名称", trigger: "blur" }]
};
const unitArray = ref([]);

// let yourPosition;
// let city;
const showMap = ref(false);
const pointData = ref([]);
const chosenData = ref([]);
const units_tag = ref([]);
let markers = [];
const units = ref([
  { text: "Home", value: "Home" },
  { text: "Office", value: "Office" }
]);

const make_unit_filter = () => {
  unitArray.value.forEach(item => {
    units.value.push({
      text: item.unitName,
      value: item.unitName
    });
    units_tag.value.push({
      value: item.unitName,
      checked: false
    });
  });
};

onMounted(async () => {
  await getAllPoints();
  tableData.value = pointData.value;
  await getAllUnits();

  window._AMapSecurityConfig = {
    securityJsCode: "701b2c8adf1951bafc116e4a916cf996"
  };
  AMapLoader.load({
    key: "dd93fce2d1e6b0eb1d3e438c7a2581c0", // 申请好的Web端开发者Key，首次调用 load 时必填
    version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
    plugins: [
      "AMap.Scale",
      "AMap.ControlBar",
      "AMap.MapType",
      "AMap.Scale",
      "AMap.ToolBar",
      "AMap.Marker",
      "AMap.PlaceSearch",
      "AMap.Geolocation"
    ] //需要使用的的插件列表，如比例尺'AMap.Scale'，支持添加多个如：['...','...']
  })
    .then(AMap => {
      map = new AMap.Map("map-container", {
        // 设置地图容器id
        viewMode: "2D", // 是否为3D地图模式
        zoom: 11 // 初始化地图级别
      });

      const placeSearch = new AMap.PlaceSearch({
        pageSize: 5, // 单页显示结果条数
        pageIndex: 1, // 页码
        map: map, // 展现结果的地图实例
        panel: "panel", // 结果列表将在此容器中进行展示。
        autoFitView: true // 是否自动调整地图视野使绘制的 Marker点都处于视口的可见范围
      });

      icon = new AMap.Icon({
        size: new AMap.Size(30, 40), //图标尺寸
        image: iconImage1, //Icon 的图像
        imageOffset: new AMap.Pixel(-2, 0), //图像相对展示区域的偏移量，适于雪碧图等
        imageSize: new AMap.Size(40, 40) //根据所设置的大小拉伸或压缩图片
      });

      icon2 = new AMap.Icon({
        size: new AMap.Size(30, 40), //图标尺寸
        image: iconImage2, //Icon 的图像
        imageOffset: new AMap.Pixel(-2, 0), //图像相对展示区域的偏移量，适于雪碧图等
        imageSize: new AMap.Size(40, 40) //根据所设置的大小拉伸或压缩图片
      });

      const marker = new AMap.Marker({
        offset: [0, 6],
        zIndex: 99
      });
      map.add(marker);

      const controlBar = new AMap.ControlBar();
      map.addControl(controlBar);

      const scale = new AMap.Scale();
      map.addControl(scale);

      const toolBar = new AMap.ToolBar();
      map.addControl(toolBar);

      // 在地图时启用定位
      // 初始化 Geolocation 插件
      // const geolocation = new AMap.Geolocation({
      //   enableHighAccuracy: true, // 是否使用高精度定位，默认：true
      //   timeout: 10000, // 设置定位超时时间，默认：无穷大
      //   offset: [20, 90], // 定位按钮的停靠位置的偏移量
      //   zoomToAccuracy: true, // 定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
      //   position: "RB" // 定位按钮的排放位置,  RB表示右下
      // });

      // map.addControl(geolocation);

      // geolocation.getCurrentPosition((status, result) => {
      //   if (status === "complete") {
      //     onComplete(result);
      //   } else {
      //     onError(result);
      //   }
      // });
      onComplete();
      // 调整地图视野以包含所有标记
      map.setFitView(markers, true);

      function onComplete() {
        // data是具体的定位信息
        // const position = data.position;
        // map.setCenter(position); // 将地图中心点设置为定位点
        // longitude.value = position.lng;
        // latitude.value = position.lat;
        // yourPosition = [position.lng, position.lat];
        // console.log("定位成功", yourPosition);
        if (pointData.value) {
          pointData.value.forEach(detail => {
            const point = [detail.mapLongitude, detail.mapLatitude];
            const label = { content: detail.mapDetailDesc, offset: [10, -10] };
            // const distance = AMap.GeometryUtil.distance(yourPosition, point);
            // const content = "距离您" + Math.round(distance) + "米";
            const detailMarker = new AMap.Marker({
              icon: icon2,
              clickable: false,
              label: label,
              // title: content,
              position: point,
              extData: detail,
              offset: [-18, -40],
              map: map
            });
            markers.push(detailMarker);
          });
        }
      }

      // function onError(data) {
      //   // 定位出错
      //   console.error("定位失败", data);
      // }

      // geolocation.getCityInfo((status, result) => {
      //   if (status === "complete") {
      //     city = result.city;
      //     placeSearch = new AMap.PlaceSearch({
      //       city: city,
      //       pageSize: 5, // 单页显示结果条数
      //       pageIndex: 1, // 页码
      //       map: map, // 展现结果的地图实例
      //       panel: "panel", // 结果列表将在此容器中进行展示。
      //       autoFitView: true // 是否自动调整地图视野使绘制的 Marker点都处于视口的可见范围
      //     });
      //   } else {
      //     onError(result);
      //   }
      // });

      // 其他插件初始化和地图相关的代码
      map.plugin(["AMap.AutoComplete"], function () {
        const autoOptions = {
          //使用联想输入的 input 的 id
          input: "searchInput"
        };
        const autocomplete = new AMap.AutoComplete(autoOptions);
        autocomplete.on("select", function (e) {
          //针对选中的poi实现自己的功能
          placeSearch.search(e.poi.name);
        });
      });
    })
    .catch(e => {
      console.log(e);
    });
});
const emit = defineEmits(["turnBack", "refreshData"]);
const turnBack = () => {
  emit("turnBack");
};

const goToMarker = row => {
  longitude.value = row.mapLongitude;
  latitude.value = row.mapLatitude;
  map.setCenter([longitude.value, latitude.value]);
};

const OpenNewMapDialog = () => {
  if (chosenData.value.length === 0) {
    ElMessage.warning("请选择点位");
    return;
  }
  addForm.mapPoints = chosenData.value;
  showNewMapDialog.value = true;
};
const ConfirmNewMap = () => {
  addFormRef.value.validate(valid => {
    if (valid) {
      console.log("New", addForm);
      request.post("/api-self/inspection/map", addForm).then(res => {
        const data = res.data;
        if (data.code === 0) {
          ElMessage.success("新建路线成功");
          turnBack();
        } else {
          ElMessage.error("新建路线失败：" + data.message);
        }
      });
    }
  });
};

const getAllPoints = async () => {
  loading.value = true;
  await request
    .get("/api-self/inspection/map/1")
    .then(res => {
      const data = res.data;
      if (data.code === 0) {
        pointData.value = data.data;
      } else {
        ElMessage.error("获取可选点位信息失败：" + data.message);
      }
      loading.value = false;
    })
    .catch(() => {
      loading.value = false;
    });
};
const getAllUnits = () => {
  request.get("/api-self/users/unit/getUnits").then(res => {
    const data = res.data;
    if (data.code === 0) {
      unitArray.value = data.data;
      make_unit_filter();
    } else {
      ElMessage.error("获取机组数据失败：" + data.message);
    }
  });
};
const tableRef = ref();
//过滤器
const filterUnit = (value, row) => {
  return row.unitName === value;
};
const clearFilter = () => {
  if (tableRef.value) {
    tableRef.value.clearFilter();
  }
};

const handleSelectionChange = selectedRows => {
  chosenData.value = selectedRows;
  chosenData.value.forEach(point => {
    let index = markers.findIndex(marker => marker.getExtData().mapDetailId === point.mapDetailId);
    if (index !== -1) {
      markers[index].setIcon(icon);
    }
  });
  // 找出未选中行，并将图标设置为 icon1
  pointData.value.forEach(point => {
    // 如果这个点不在 chosenData 中，则它是取消选择的点
    if (!chosenData.value.some(selected => selected.mapDetailId === point.mapDetailId)) {
      let index = markers.findIndex(marker => marker.getExtData().mapDetailId === point.mapDetailId);
      if (index !== -1) {
        markers[index].setIcon(icon2);
      }
    }
  });
};

onUnmounted(() => {
  map?.destroy();
});
const showMapOrNot = () => {
  showMap.value = !showMap.value;
};

const tags = ref([]);
const TagChange = item => {
  item.checked = !item.checked;
  if (item.checked) {
    if (!tags.value.includes(item.value)) {
      tags.value.push(item.value);
    }
  } else {
    const index = tags.value.indexOf(item.value);
    if (index !== -1) {
      tags.value.splice(index, 1);
    }
  }
  filteredPointData();
  console.log("tags", tags.value);
};

const tableData = ref([]);

const filteredPointData = () => {
  if (tags.value.length) {
    tableData.value = pointData.value.filter(point => {
      return !tags.value.length || tags.value.includes(point.unitName);
    });
  } else {
    tableData.value = pointData.value;
  }
};
</script>

<style scoped>
#map-container {
  width: 100%;
  height: 74vh;
}
.marker-list {
  width: 100%;
  height: 74vh;
}
#panel {
  position: fixed;
  top: 200px;
  right: 20px;
  width: 300px;
  max-height: 90%;
  overflow-y: auto;
  background-color: white;
  border-bottom: solid 0 silver;
}
.custom-table :deep(.el-table__header-wrapper thead tr th) {
  color: #000000;
  text-align: center;
  background-color: #fafafa;
}
.custom-table :deep(.el-table__body-wrapper tbody tr td) {
  text-align: center; /* 单元格内容居中 */
}
</style>
